import React, { useCallback, useEffect } from "react"
import { connect, useDispatch, useSelector } from "react-redux"
import useInput from "../hooks/useInput"
import { navigate } from "gatsby"
import { Button, message } from "antd"
function Login() {
  const email = useInput("")
  const password = useInput("")
  const userReducer = useSelector(state => state.user)
  useEffect(() => {
    if (userReducer.user) {
      navigate("/")
    }
  }, [userReducer.user])
  const dispatch = useDispatch()
  const handleSubmit = useCallback(
    async e => {
      // console.log(e)
      e.preventDefault()
      const passwordValue = password.input.value
      const emailValue = email.input.value
      console.log(emailValue)
      console.log(passwordValue)
      const res = await dispatch({
        type: "user/login",
        payload: {
          user: {
            email: emailValue,
            password: passwordValue,
          },
        },
      })
      console.log("res", res)
      if (!res) {
        message.error("用户名或密码错误")
      }
    },
    [password.input.value, email.input.value]
  )
  return (
    <div className="auth-page">
      <Button type="primary">点我</Button>
      <div className="container page">
        <div className="row">
          <div className="col-md-6 offset-md-3 col-xs-12">
            <h1 className="text-xs-center">Sign up</h1>
            <ul className="error-messages">
              <li>That email is already taken</li>
            </ul>
            <form onSubmit={handleSubmit}>
              <fieldset className="form-group">
                <input
                  className="form-control form-control-lg"
                  type="text"
                  placeholder="Email"
                  {...email.input}
                />
              </fieldset>
              <fieldset className="form-group">
                <input
                  className="form-control form-control-lg"
                  type="password"
                  placeholder="Password"
                  {...password.input}
                />
              </fieldset>
              <button className="btn btn-lg btn-primary pull-xs-right">
                Sign up
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
}
export default Login
